package com.bdmc.web.controller.api;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bdmc.base.domain.BaseDevice;
import com.bdmc.base.service.IBaseDeviceService;
import com.bdmc.common.core.domain.AjaxResult;
import com.bdmc.common.utils.MapDistance;
import com.bdmc.device.domain.DevGpsHistory;
import com.bdmc.device.domain.DevGpsRealtime;
import com.bdmc.device.service.IDevGpsHistoryService;
import com.bdmc.device.service.IDevGpsRealtimeService;
import com.bdmc.web.controller.api.model.CarData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/car")
public class CarController {
    @Autowired
    private IDevGpsRealtimeService realtimeService;
    @Autowired
    private IDevGpsHistoryService historyService;
    @Autowired
    private IBaseDeviceService deviceService;

    static List<BaseDevice> deviceList;

    @PostConstruct
    public void init(){
        LambdaQueryWrapper<BaseDevice> w = Wrappers.lambdaQuery();
        w.eq(BaseDevice::getDeviceType,"portable_locator");
        deviceList = deviceService.list(w);
    }

    @PostMapping("/location")
    public AjaxResult<Void> location(@RequestBody JSONArray jsonArray) {
        List<CarData> carDataList = JSONUtil.toList(jsonArray, CarData.class);
        LocalDateTime now = LocalDateTime.now();
        for (CarData carData : carDataList) {
            DevGpsRealtime realtime = new DevGpsRealtime();
            DevGpsHistory history = new DevGpsHistory();
            deviceList.stream().filter(r->r.getDevicePhoneNum().equals(carData.getDeviceId())).findFirst().ifPresent(device -> {
                realtime.setDeviceId(device.getDeviceId());
                realtime.setDevicePhoneNum(device.getDevicePhoneNum());
                history.setDeviceId(device.getDeviceId());
            });
            //暂时不知道为什么会有deviceId 为空的数据  反正先给他 continue
            if(realtime.getDeviceId() == null){
                continue;
            }
            realtime.setWgs84Lat(getDecimalStr(carData.getLatitude()));
            realtime.setWgs84Lng(getDecimalStr(carData.getLongitude()));
            double[] gcj02 = MapDistance.wgs84togcj02(Double.parseDouble(realtime.getWgs84Lng()), Double.parseDouble(realtime.getWgs84Lat()));
            realtime.setLat(String.valueOf(gcj02[0]));
            realtime.setLng(String.valueOf(gcj02[1]));
            realtime.setSpeed(new BigDecimal(carData.getSpeed()));
            realtime.setOnlineStatus(1);

            history.setLat(realtime.getLat());
            history.setLng(realtime.getLng());
            history.setSpeed(realtime.getSpeed());

            Instant instant = Instant.ofEpochMilli(carData.getDeviceTime());
            LocalDateTime dataTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();

            realtime.setDataTime(dataTime);
            history.setDataTime(dataTime);
            realtime.setUpdateTime(dataTime);

            realtime.setCreateTime(now);
            history.setCreateDate(now);
            LambdaQueryWrapper<DevGpsRealtime> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(DevGpsRealtime:: getDeviceId,realtime.getDeviceId()); // 设置唯一键条件
            realtimeService.saveOrUpdate(realtime,queryWrapper);//插入或更新
            historyService.save(history);
        }
        log.info("成功处理车辆位置数量："+carDataList.size());
        return AjaxResult.success();
    }

    private String getDecimalStr(int number ){
        // 使用BigDecimal将数字保留指定小数位数
        BigDecimal bigDecimal = new BigDecimal(number).divide(new BigDecimal(1000000));
        bigDecimal = bigDecimal.setScale(6, RoundingMode.HALF_UP); // 使用四舍五入
        // 将BigDecimal转换为字符串
        return bigDecimal.toString();
    }
}
